// Simple client-side auth using localStorage
const USERS_KEY = 'streamvue_users'
const CURRENT_KEY = 'streamvue_current_user'
const MEMBER_HISTORY_KEY = 'streamvue_member_history'

function loadUsers() {
  try { return JSON.parse(localStorage.getItem(USERS_KEY) || '[]') } catch { return [] }
}
function saveUsers(users) { localStorage.setItem(USERS_KEY, JSON.stringify(users)) }

export function getCurrentUser() {
  try {
    const user = JSON.parse(localStorage.getItem(CURRENT_KEY) || 'null')
    if (user) {
      // 获取完整用户信息，包括会员状态
      const users = loadUsers()
      const fullUser = users.find(u => u.username === user.username)
      if (fullUser) {
        return {
          ...user,
          isMember: fullUser.isMember || false,
          memberExpires: fullUser.memberExpires || null,
          memberLevel: fullUser.memberLevel || 'basic'
        }
      }
    }
    return user
  } catch { return null }
}
// 添加一个简单的事件通知，便于组件监听登录状态变化
function notify() {
  try { window.dispatchEvent(new Event('auth-changed')) } catch (e) { /* ignore */ }
}
export function logout() { localStorage.removeItem(CURRENT_KEY); notify() }

export function register(username, password) {
  username = String(username || '').trim()
  password = String(password || '')
  if (!username || !password) throw new Error('请输入用户名和密码')
  if (username.length < 2) throw new Error('用户名长度至少 2 个字符')
  if (password.length < 4) throw new Error('密码长度至少 4 个字符')
  const users = loadUsers()
  if (users.some(u => u.username === username)) throw new Error('用户名已存在')
  // 添加会员相关字段，新注册用户默认为非会员
  const user = {
    username, 
    password,
    isMember: false,
    memberExpires: null,
    memberLevel: 'basic',
    createdAt: new Date().toISOString()
  }
  users.push(user)
  saveUsers(users)
  localStorage.setItem(CURRENT_KEY, JSON.stringify({ 
    username, 
    isMember: false,
    memberExpires: null,
    memberLevel: 'basic'
  }))
  notify()
  return { username, isMember: false, memberLevel: 'basic' }
}

export function login(username, password) {
  username = String(username || '').trim()
  password = String(password || '')
  const users = loadUsers()
  const ok = users.find(u => u.username === username && u.password === password)
  if (!ok) throw new Error('用户名或密码错误')
  
  // 检查会员是否过期
  const now = new Date()
  let isMember = ok.isMember || false
  let memberExpires = ok.memberExpires || null
  let memberLevel = ok.memberLevel || 'basic'
  
  if (isMember && memberExpires && new Date(memberExpires) < now) {
    // 会员过期，更新状态
    isMember = false
    memberExpires = null
    memberLevel = 'basic'
    ok.isMember = false
    ok.memberExpires = null
    ok.memberLevel = 'basic'
    saveUsers(users)
  }
  
  localStorage.setItem(CURRENT_KEY, JSON.stringify({ 
    username, 
    isMember, 
    memberExpires, 
    memberLevel 
  }))
  notify()
  return { username, isMember, memberLevel }
}

export function changePassword(oldPassword, newPassword) {
  const current = getCurrentUser()
  if (!current) throw new Error('请先登录')
  const users = loadUsers()
  const idx = users.findIndex(u => u.username === current.username)
  if (idx === -1) throw new Error('用户不存在')
  if (String(users[idx].password) !== String(oldPassword)) throw new Error('旧密码不正确')
  if (!newPassword || String(newPassword).length < 8) throw new Error('新密码长度至少 8 个字符')
  users[idx].password = String(newPassword)
  saveUsers(users)
  return true
}

// 会员相关功能
export function getMemberInfo(username) {
  const users = loadUsers()
  const user = users.find(u => u.username === username)
  if (!user) return { isMember: false, memberExpires: null, memberLevel: 'basic' }
  
  // 检查会员是否过期
  const now = new Date()
  let isMember = user.isMember || false
  let memberExpires = user.memberExpires || null
  let memberLevel = user.memberLevel || 'basic'
  
  if (isMember && memberExpires && new Date(memberExpires) < now) {
    isMember = false
    memberExpires = null
    memberLevel = 'basic'
    user.isMember = false
    user.memberExpires = null
    user.memberLevel = 'basic'
    saveUsers(users)
  }
  
  return { isMember, memberExpires, memberLevel }
}

// 开通或续费会员
export function activateMember(username, months = 1, level = 'standard') {
  const users = loadUsers()
  const idx = users.findIndex(u => u.username === username)
  if (idx === -1) throw new Error('用户不存在')
  
  const now = new Date()
  const user = users[idx]
  const isRenewal = user.isMember && user.memberExpires
  
  // 会员等级定义
  const memberLevels = {
    standard: { name: '标准会员', color: '#00a1d6', price: 19, features: ['无广告观看', '高清画质', '基础下载'] },
    premium: { name: '高级会员', color: '#8b5cf6', price: 39, features: ['无广告观看', '超高清画质', '高速下载', '专属内容'] }
  }
  
  if (!memberLevels[level]) level = 'standard'
  
  // 计算过期时间
  let expires = user.memberExpires && user.isMember ? new Date(user.memberExpires) : now
  expires.setMonth(expires.getMonth() + months)
  
  // 更新会员信息
  user.isMember = true
  user.memberExpires = expires.toISOString()
  user.memberLevel = level
  user.lastMemberUpdate = now.toISOString()
  user.memberSource = user.memberSource || 'direct' // direct表示直接购买
  
  saveUsers(users)
  
  // 添加历史记录
  const planName = memberLevels[level].name
  addMemberHistory(username, isRenewal ? '续费会员' : '开通会员', 
    `${isRenewal ? '续费' : '开通'}${planName}，有效期${months}个月`)
  
  // 更新当前登录用户信息
  const current = getCurrentUser()
  if (current && current.username === username) {
    localStorage.setItem(CURRENT_KEY, JSON.stringify({ 
      ...current,
      isMember: true,
      memberExpires: expires.toISOString(),
      memberLevel: level
    }))
    notify()
  }
  
  return {
    isMember: true,
    memberExpires: expires.toISOString(),
    memberLevel: level,
    memberInfo: memberLevels[level],
    isRenewal
  }
}

// 加载会员历史记录
function loadMemberHistory() {
  try { return JSON.parse(localStorage.getItem(MEMBER_HISTORY_KEY) || '{}') } catch { return {} }
}

// 保存会员历史记录
function saveMemberHistory(history) {
  localStorage.setItem(MEMBER_HISTORY_KEY, JSON.stringify(history))
}

// 添加会员历史记录
function addMemberHistory(username, action, details) {
  const history = loadMemberHistory()
  if (!history[username]) {
    history[username] = []
  }
  
  history[username].unshift({
    date: new Date().toISOString(),
    action,
    details
  })
  
  // 保留最近100条记录
  if (history[username].length > 100) {
    history[username] = history[username].slice(0, 100)
  }
  
  saveMemberHistory(history)
  return history[username]
}

// 获取会员历史记录
export function getMemberHistory(username) {
  const history = loadMemberHistory()
  return history[username] || []
}

// 取消会员
export function cancelMember(username) {
  const users = loadUsers()
  const idx = users.findIndex(u => u.username === username)
  if (idx === -1) throw new Error('用户不存在')
  
  users[idx].isMember = false
  users[idx].memberExpires = null
  users[idx].memberLevel = 'basic'
  users[idx].lastMemberUpdate = new Date().toISOString()
  
  saveUsers(users)
  
  // 添加历史记录
  addMemberHistory(username, '取消会员', '已取消会员服务')
  
  // 更新当前登录用户信息
  const current = getCurrentUser()
  if (current && current.username === username) {
    localStorage.setItem(CURRENT_KEY, JSON.stringify({ 
      ...current,
      isMember: false,
      memberExpires: null,
      memberLevel: 'basic'
    }))
    notify()
  }
  
  return { isMember: false, memberLevel: 'basic' }
}

// 赠送会员给好友
export function giftMember(fromUsername, toUsername, months = 1, level = 'standard') {
  const users = loadUsers()
  
  // 检查赠送者是否存在
  const fromIdx = users.findIndex(u => u.username === fromUsername)
  if (fromIdx === -1) throw new Error('赠送者不存在')
  
  // 检查接收者是否存在
  const toIdx = users.findIndex(u => u.username === toUsername)
  if (toIdx === -1) throw new Error('接收者不存在')
  
  // 会员等级定义
  const memberLevels = {
    standard: { name: '标准会员', color: '#00a1d6', price: 19, features: ['无广告观看', '高清画质', '基础下载'] },
    premium: { name: '高级会员', color: '#8b5cf6', price: 39, features: ['无广告观看', '超高清画质', '高速下载', '专属内容'] }
  }
  
  if (!memberLevels[level]) level = 'standard'
  
  // 计算过期时间
  const now = new Date()
  const toUser = users[toIdx]
  let expires = toUser.memberExpires && toUser.isMember ? new Date(toUser.memberExpires) : now
  expires.setMonth(expires.getMonth() + months)
  
  // 更新接收者会员信息
  toUser.isMember = true
  toUser.memberExpires = expires.toISOString()
  toUser.memberLevel = level
  toUser.lastMemberUpdate = now.toISOString()
  toUser.memberSource = 'gift'
  toUser.memberGiftFrom = fromUsername
  
  saveUsers(users)
  
  // 添加历史记录
  const planName = memberLevels[level].name
  addMemberHistory(fromUsername, '赠送会员', `赠送给${toUsername} ${planName}，有效期${months}个月`)
  addMemberHistory(toUsername, '收到会员赠送', `收到来自${fromUsername}的${planName}，有效期${months}个月`)
  
  // 更新当前登录用户信息
  const current = getCurrentUser()
  if (current && current.username === toUsername) {
    localStorage.setItem(CURRENT_KEY, JSON.stringify({ 
      ...current,
      isMember: true,
      memberExpires: expires.toISOString(),
      memberLevel: level
    }))
    notify()
  }
  
  return {
    isMember: true,
    memberExpires: expires.toISOString(),
    memberLevel: level,
    memberInfo: memberLevels[level],
    giftFrom: fromUsername
  }
}

// 检查用户是否有某个权限
export function checkMemberPermission(username, permission) {
  const memberInfo = getMemberInfo(username)
  if (!memberInfo.isMember) return false
  
  const permissions = {
    'no-ads': true, // 所有会员都无广告
    'hd-quality': true, // 所有会员都有高清
    '4k-quality': memberInfo.memberLevel === 'premium', // 只有高级会员有4K
    'download': true, // 所有会员都能下载
    'high-speed': memberInfo.memberLevel === 'premium', // 只有高级会员有高速
    'exclusive-content': memberInfo.memberLevel === 'premium', // 只有高级会员有专属内容
    'multi-device': memberInfo.memberLevel === 'premium' // 只有高级会员有多设备
  }
  
  return permissions[permission] || false
}